package com.huhao.wshare.Friends;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.huhao.wshare.Config.GET_FRIEND_LIST;
import androidx.recyclerview.widget.DividerItemDecoration;

import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.LoginActivity;
import com.huhao.wshare.R;

public class SearchActivity extends BaseActivity {

    private EditText etSearch;
    private FriendAdapter friendAdapter;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_search);

        // 初始化视图组件
        etSearch = findViewById(R.id.et_search);
        RecyclerView recyclerViewSearchResults = findViewById(R.id.recyclerView_search_results);

        // 设置 RecyclerView 布局管理器
        recyclerViewSearchResults.setLayoutManager(new LinearLayoutManager(this));

        // 添加系统默认分隔线
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        recyclerViewSearchResults.addItemDecoration(dividerItemDecoration);

        // 初始化适配器并设置给 RecyclerView
        friendAdapter = new FriendAdapter(new ArrayList<>());
        recyclerViewSearchResults.setAdapter(friendAdapter);

        // 从 SharedPreferences 中获取 token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        token = sp.getString("token", null);

        if (token != null) {
            // 获取好友列表
            fetchFriendList();
        } else {
            // 用户未登录，跳转到登录页
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }

        // 为输入框添加文本变化监听器
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 实时过滤好友列表
                friendAdapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 不需要实现
            }
        });
    }

    private void fetchFriendList() {
        // 构建请求头，包含 Authorization
        Request request = new Request.Builder()
                .url(GET_FRIEND_LIST)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送网络请求
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(SearchActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String respStr = response.body().string();
                    runOnUiThread(() -> handleFriendListResponse(respStr));
                } else {
                    runOnUiThread(() -> Toast.makeText(SearchActivity.this, "获取好友列表失败，请稍后重试", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void handleFriendListResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONArray data = json.optJSONArray("data");
                if (data != null) {
                    List<Friend> friendList = new ArrayList<>();
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject friendJson = data.getJSONObject(i);
                        int id = friendJson.optInt("friendId");
                        String account = friendJson.optString("account");
                        String username = friendJson.optString("username");
                        String signs = friendJson.optString("signs");
                        String remark = friendJson.optString("remark");
                        String avatar = friendJson.optString("avatar");
                        String gender = friendJson.optString("gender");
                        friendList.add(new Friend(id, account, username, signs, remark, avatar, gender));
                    }
                    friendAdapter.updateFriendList(friendList);
                }
            } else {
                Toast.makeText(this, json.optString("message"), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "解析好友列表失败", Toast.LENGTH_SHORT).show();
            Log.e("SearchActivity", "解析 JSON 失败", e);
        }
    }
}